import styles from './index.module.scss'
import cm from 'classnames'
import Responsive from '@c/responsive'
import Footer from '@c/footer'
import { useEffect, useState } from 'react'
import dynamic from 'next/dynamic'
import { getPublishSource, getDailyTasks } from '@/api/score'
import { useRouter } from 'next/router'
import { useShowLogin } from '@/utils/hooks'
import { userInfo } from '@/store'
import { useRecoilValue } from 'recoil'
import message from '@c/message'
import { scorePageReport, scorePageClickReport } from '@/utils/report'

const ModalScoreJIfen = dynamic(() => import('@c/modal/modal-score-jifen'))
const ModalScoreDetail = dynamic(() => import('@c/modal/modal-score-detail'))
const Loading = dynamic(() => import('@c/request-loading'))

const webObj = {
  1: ({ showLogin }) => {
    if (localStorage.getItem('token')) {
      message({ content: '当前任务已完成' })
      return
    }
    showLogin()
  },
  2: ({ router }) => router.push('/'),
  3: ({ router }) => router.push('/live'),
  4: ({ router }) => router.push('/invite'),
  5: ({ router, url }) => {
    if (url.startsWith('http')) {
      window.open(url, '_blank')
    } else {
      router.push(url)
    }
  }
}

const Index = () => {
  const showLogin = useShowLogin()
  const router = useRouter()
  const user = useRecoilValue(userInfo)
  const [jifenModal, toggleJifenModal] = useState(false)
  const [jifenDetail, toggleJifenDetail] = useState(false)
  const [score, setScore] = useState(0)
  const [list, setList] = useState(null)
  const getMyScore = async () => {
    if (!localStorage.getItem('token')) {
      return
    }
    const res = await getPublishSource()
    setScore(res?.data?.minePoints)
  }
  const getTasks = async () => {
    const res = await getDailyTasks()
    const data = res.data?.filter(item => !item.isComplete) || []
    if (data.length % 2 == 1) {
      data.push({ isFake: true })
    }
    setList(data)
  }
  //打开积分明细
  const openDetail = () => {
    scorePageClickReport({
      points_button: '积分明细'
    })
    if (!user.token) {
      showLogin()
      return
    }
    toggleJifenDetail(true)
  }
  // 打开积分兑换
  const openConvert = () => {
    scorePageClickReport({
      points_button: '积分兑换'
    })
    if (!user.token) {
      showLogin()
      return
    }
    toggleJifenModal(true)
  }
  // 去完成
  const toFinish = item => {
    scorePageClickReport({
      points_button: item.title
    })
    if (!user.token) {
      showLogin()
      return
    }
    if (item.isComplete) {
      return
    }
    webObj[item['webRedirectType']]?.({ showLogin, router, url: item.webRedirectUrl })
  }
  useEffect(() => {
    getMyScore()
    getTasks()
    setTimeout(() => {
      try {
        scorePageReport({ points_source: '活动首页' })
      } catch (error) {}
    }, 1000)
  }, [])

  return (
    <div className={styles.scoreMain}>
      <div className={styles.scoreHeader}>
        <div className={styles.header}>
          <img src="/images/score-head-bg.webp" alt="" className={styles.imgBg} />
          <img src="/images/user.png" alt="" className={styles.img} />
        </div>
        <div className={styles.score}>
          <span className={styles.span1}>我的积分：</span>
          {user?.token ? (
            <>
              <span className={styles.span2}>{score}</span>
              <img src="/images/corn.webp" alt="" className={styles.img} />
            </>
          ) : (
            <span className="text-white text-lg">--</span>
          )}
        </div>
        <div className={styles.menu}>
          <div className={cm(styles.menuItem, 'mr-5')}>
            <span onClick={openDetail}>积分明细</span>
            <img src="/images/score-arrow.png" alt="积分明细" />
          </div>
          <div className={styles.menuItem}>
            <span onClick={openConvert}>积分兑换</span>
            <img src="/images/score-arrow.png" alt="积分兑换" />
          </div>
        </div>
      </div>
      <div className={styles.task}>
        {list ? (
          list.length ? (
            list.map((item, index) => {
              if (item.isFake) {
                return <div className={cm(styles.tasksItem, styles.itemFake)} key={index}></div>
              }
              return (
                <div className={styles.tasksItem} key={index}>
                  <div>
                    <p className={styles.tips}>
                      {item.title}
                      {item.iconTitle && (
                        <span className={cm(styles.type, item.iconTitle == '最热' ? styles.typeRed : '')}>
                          {item.iconTitle}
                        </span>
                      )}
                    </p>
                    <div className={styles.jifen}>
                      <img src="/images/corn.webp" className={styles.img} alt="" />
                      <span className={styles.span}>+{item.point}</span>
                    </div>
                  </div>
                  <div
                    className={cm(styles.btn, item.isComplete ? styles.finished : styles.toFinish)}
                    onClick={() => toFinish(item)}
                  >
                    {item.isComplete ? '已完成' : '去完成'}
                  </div>
                </div>
              )
            })
          ) : null
        ) : (
          <Loading />
        )}
      </div>
      <p className={styles.noMore}>暂无更多积分任务～</p>
      <Responsive>
        <Footer />
      </Responsive>
      {jifenModal && <ModalScoreJIfen score={score} updateScore={getMyScore} onClose={() => toggleJifenModal(false)} />}
      {jifenDetail && <ModalScoreDetail onClose={() => toggleJifenDetail(false)} />}
    </div>
  )
}
export default Index

export async function getServerSideProps() {
  return {
    props: {
      layoutProps: {
        noSomeMetaInfo: false,
        title: '积分兑换免费解锁会员',
        desc: '积分兑换免费解锁会员'
      }
    }
  }
}
